<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ref, watch } from 'vue'

const userStore = useUserStore()

// 解决路由懒加载情况下，刷新页面导致菜单项高亮闪烁的问题
const activeIndex = ref('')
const router = useRouter()
const route = router.currentRoute
// 路由准备就绪后，再设置activeIndex，否则route.value.path会来回切换，导致菜单项高亮闪烁
router.isReady().then(() => {
    // 开发环境下打印日志
    if (import.meta.env.DEV) console.log('router isReady', route.value.path)
    activeIndex.value = route.value.path
    // 监听路由变化，更新activeIndex
    watch(
        () => route.value.path,
        (path) => {
            if (import.meta.env.DEV) console.log('router path change', path)
            activeIndex.value = path
        }
    )
})
// 监听用户登录状态，登录成功后跳转到首页
watch(
    () => userStore.isLogged,
    (isLogged) => {
        if (isLogged) {
            router.push('/')
        }
    }
)
</script>

<template>
    <el-container>
        <el-header>
            <el-menu
                :default-active="activeIndex"
                :ellipsis="false"
                class="menu"
                mode="horizontal"
                router>
                <el-text style="font-size: var(--el-font-size-extra-large)" tag="b">
                    {{ route.name }}
                </el-text>
                <!-- 与ellipsis配合，将div之后的菜单项都放右侧 -->
                <div class="flex-grow" />
                <el-menu-item index="/">首页</el-menu-item>
                <el-menu-item index="/about">关于</el-menu-item>
            </el-menu>
        </el-header>

        <el-main>
            <!-- RouterView渲染通过前端路由映射过来的组件 -->
            <RouterView />
        </el-main>
    </el-container>
</template>

<style scoped>
/* 禁止用户选中菜单文本 */
.menu {
    user-select: none;
}

/* 将一行填满,配合ellipsis使用可将菜单项全挤在右侧 */
.flex-grow {
    flex-grow: 1;
}
</style>